import React, { useMemo } from "react";
import { Radio, Form } from "antd";
import { genWidget } from "../core";
import ItemLayout, { WrapProps } from "./formLabel";

export const genRadioWidget = (c: WidgetCategory): RadioWidget => {
  const base = genWidget(c);
  return {
    ...base,
    label: "单选",
    placeholder: "请选择",
    options: [
      {
        label: "选项1",
        value: "1",
      },
      {
        label: "选项2",
        value: "2",
      },
    ],
  };
};

const RadioWidgetRender = (props: WrapProps<RadioWidget>) => {
  const { uuid, options, name, isRequired, placeholder, isview } = props;
  const hodleList = useMemo(
    () => options?.filter((x) => x.label && x.value) || [],
    [options]
  );
  return (
    <ItemLayout {...props}>
      {!isview && (
        <Radio.Group id={uuid} style={{ paddingTop: 6 }}>
          {hodleList.map((opt, i) => (
            <Radio value={opt.value} key={i}>
              {opt.label}
            </Radio>
          ))}
        </Radio.Group>
      )}
      {isview && (
        <Form.Item
          name={name}
          required={isRequired}
          rules={[
            {
              required: isRequired,
              message: placeholder,
            },
          ]}
        >
          <Radio.Group id={uuid}>
            {hodleList.map((opt, i) => (
              <Radio value={opt.value} key={i}>
                {opt.label}
              </Radio>
            ))}
          </Radio.Group>
        </Form.Item>
      )}
    </ItemLayout>
  );
};

export default RadioWidgetRender;
